#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "dt_btn_util.h"

static void Button_Callback(const char* sender, BtnEvent event)
{
    printf("[dt4sw] Button_Callback() : %s -> %d\n", sender, event);

    if( event == Pressed )     { /* Pressed == 1     按下事件处理代码 */ }
    if( event == LongPressed ) { /* LongPressed == 2 长按事件处理代码 */ }
    if( event == Released )    { /* Released == 4    释放事件处理代码 */ }
}

static void* DTBtnDemo_Task(const char* arg)
{
    int ret = 0;

    printf("[dt4sw] DTBtnDemo_Task()\n");

    (void)arg;

    ret += DTButton_Init(); // 初始化按键事件处理上下文

    /* 设置GPIO_8按键的回调函数，同时需要响应按下，释放以及长按三个事件 */
    /* 按键触发顺序： Pressed -> LongPressed(optional) -> Released */
    ret += DTButton_Enable("GPIO_8", Button_Callback, Pressed | LongPressed | Released);

    /* 设置GPIO_5按键的回调函数，只需响应释放事件 */
    ret += DTButton_Enable("GPIO_5", Button_Callback, Released);

    if( ret == 0 )
    {
        while(1) 
        {
            usleep(100000);
        }

        DTButton_Disable("GPIO_8");  // 取消 GPIO_8 按键的所有按键事件
        DTButton_Disable("GPIO_5");  // 取消 GPIO_5 按键的所有按键事件

        DTButton_Deinit(); // 关闭按钮事件处理上下文
    }
    else
    {
        printf("[dt4sw] Falied to enable button!\n");
    }

    return NULL;
}

static void DTBtnDemo_Entry(void)
{
    osThreadAttr_t attr = {0};

    printf("[dt4sw] DTBtnDemo_Entry()\n");

    attr.name = "DTBtnDemo_Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024;
    attr.priority = osPriorityNormal;

    if (osThreadNew((osThreadFunc_t)DTBtnDemo_Task, NULL, &attr) == NULL)
    {
        printf("[dt4sw] Falied to create LedTask!\n");
    }
}

SYS_RUN(DTBtnDemo_Entry);